<template>
  <div class="page-container">
    <!-- 面包屑部分 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>消息中心</el-breadcrumb-item>
        <el-breadcrumb-item>模板管理(短信邮件)</el-breadcrumb-item>
        <el-breadcrumb-item>模板管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar w100">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item label="模板ID：">
            <el-input v-model.trim="filters.id"   @input="filters.id=filters.id.replace(/[^\d.]/g,'')"   maxlength="80" placeholder="请输入模板ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="模板名称：">
            <el-input v-model.trim="filters.templateName" maxlength="80" placeholder="请输入模板名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="模板类型：">
            <el-select v-model="filters.templateType" placeholder="全部" clearable :popper-append-to-body="false">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row class="search-button-noborder">
          <el-form-item>
            <kt-button :label="$t('action.reset')" class="resetButton" @click="resetForm('filters')" :size="size" icon="el-icon-refresh"/>
          </el-form-item>
           <el-form-item>
            <kt-button icon="el-icon-search" :label="'搜索'" class="searchButton" @click="search" :size="size"/>
          </el-form-item>
          <el-form-item>
            <kt-button label="新增" class="searchButton" @click="addTemplate()" :size="size" perms="mem:rule:add"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!--表格内容栏-->
    <el-table :data="tableData"
              :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
              :highlight-current-row="true"
              :max-height="1500"
              :size="size"
              v-loading="loading"
              style="width: 100%"

    >
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="templateName" label="模板名称">
        <template slot-scope="scope">
          <span>{{scope.row.templateName==null||scope.row.templateName==''?'-':scope.row.templateName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="templateType" label="模板类型" :formatter="typeFormatter">
      </el-table-column>
      <el-table-column prop="templateContent" label="内容正文">
        <template slot-scope="scope">
          <span>{{scope.row.templateContent==null||scope.row.templateContent==''?'-':scope.row.templateContent}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime==null||scope.row.createTime==''?'-':scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" label="创建人">
      <template slot-scope="scope">
        <span>{{scope.row.creatorName==null||scope.row.creatorName==''?'-':scope.row.creatorName}}</span>
      </template>
    </el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormatter">
      </el-table-column>
      <el-table-column  fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="handleLook(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页栏v-if="scope.row.status == 1"-->
    <div class="toolbar" style="padding:10px;">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="refreshPageRequest"
        :current-page="pageRequest.pageNum"
        :page-size="pageRequest.pageSize"
        :total="totalSize"
        style="float:right;"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>
    <!--模板新增-->
    <el-dialog title="新增模板"  :visible.sync="editDialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm"  :rules="dataFormRules" ref="dataForm" :size="size">
        <el-form-item label="模板名称：" prop="templateName" label-width="92px" class="mb30">
          <el-input v-model.trim="dataForm.templateName" clearable   maxlength="20"
                    auto-complete="off"
                    placeholder="输入模板名称" class="w760 mr10"></el-input>
          <!-- <div class="desc"></div> -->
          <el-tooltip
                popper-class="atooltip"
                effect="dark"
                content="请输入1-50个字符"
                placement="right"
                class="tipsInfo"
              >
                <span class="icon">!</span>
              </el-tooltip>
        </el-form-item>
        <el-form-item label="模板类型：" prop="templateType" label-width="92px" class="mb30">
          <el-select v-model="dataForm.templateType"
                     placeholder="请输入模板类型" @change="changeTemplateType" class="w760" >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容：" v-if="showTemplateContent" prop="templateContent" label-width="92px mb10">
          <el-input type="textarea" clearable v-model.trim="dataForm.templateContent" auto-complete="off"
                    placeholder="输入模板内容" class="w760" :rows="10"></el-input>
                    <el-tooltip
                popper-class="atooltip"
                effect="dark"
                content="1.说明：模板支持增加变量，变量的部分需输入“ ${n} ”，其中 n = 1、2、3、4…；2.例如：五一长假，${1} 统统八折，抢到就是赚到，分享好友享更多好礼！点击${2} 立即领取。回T退订"
                placement="bottom"
                class="tipsInfo"
              >
                <span class="icon">!</span>
              </el-tooltip>
          <!-- <div class="ml90 mb10 mt10"><span class="desc">· 说明：模板支持增加变量，变量的部分需输入“ ${n} ”，其中 n = 1、2、3、4…</span></div>
          <div class="ml90 mb60"><span class="desc">· 例如：五一长假，${1} 统统八折，抢到就是赚到，分享好友享更多好礼！点击${2} 立即领取。回T退订</span></div> -->
        </el-form-item>
        <el-form-item label="模板内容："  v-if="!showTemplateContent" prop="templateContent" >
          <el-upload
            class="avatar-uploader"
            :action="imgUpload"
            multiple
            :on-success="uploadSuccess"
            :show-file-list="false"
          >
          </el-upload>
          <quill-editor ref="myTextEditor" v-model="dataForm.templateContent" class="myQuillEditor w760"
                        :options="editorOption"
                        style="margin-left:90px;height:200px;margin-bottom:80px"

          />
          <el-tooltip
                popper-class="atooltip"
                effect="dark"
                content="1.说明：模板支持增加变量，变量的部分需输入“ ${n} ”，其中 n = 1、2、3、4…；2.例如：五一长假，${1} 统统八折，抢到就是赚到，分享好友享更多好礼！点击${2} 立即领取。回T退订"
                placement="bottom"
                class="tipsInfo"
              >
                <span class="icon">!</span>
              </el-tooltip>
          <!-- <div class="ml90 mb10 "><span class="desc"></span></div>
          <div class="ml90 mb60"><span class="desc"></span></div> -->
        </el-form-item>
        <!-- <el-form-item >

        </el-form-item>
        <el-form-item >

        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false" class="cancelButton mr60">{{ $t("action.cancel")}}</el-button>
        <el-button :size="size" class="searchButton" @click.native="submitForm" :loading="editLoading">保存
        </el-button
        >
      </div>
    </el-dialog>

    <!--查看-->
    <el-dialog title="查看模板" :visible.sync="editDialogLookVisible" :close-on-click-modal="false">
      <el-form :model="dataLookForm"  ref="dataLookForm" :size="size">
        <el-form-item  prop="templateName" required class="mb30">
          <span style="color:red">*</span>
          <span class="color333 font16">模板名称：</span>
          <span class="color333 font16">{{dataLookForm.templateName}}</span>
        </el-form-item>
        <el-form-item  prop="templateType" class="mb30">
          <span style="color:red">*</span>
          <span class="color333 font16">模板类型：</span>
          <span class="color333 font16">{{dataLookForm.templateType}}</span>
        </el-form-item>
        <el-form-item  prop="templateContent" class="mb60">
          <span style="color:red">*</span>
          <span class="color333 font16">模板内容：</span>
          <span v-html="dataLookForm.templateContent"></span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" type="primary" @click.native="editDialogLookVisible = false">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {quillEditor} from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import * as Quill from 'quill'  //引入编辑器
  import {exportExcel} from "@/utils/excel";
  import CyTable from "@/views/Core/JicTable";
  import LabelSelection from "@/components/AutoMarket/labelSelection";
  import KtButton from "@/views/Core/KtButton";
  import {format} from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import {validatePhone, validateContacts, isEmail, isNumber} from '@/utils/validate'
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],
    [{'indent': '-1'}, {'indent': '+1'}],
    [{'direction': 'rtl'}],
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],
    [{'align': []}],
    ['link', 'image'],
    ['clean']
  ]
  export default {
    components: {
      CyTable,
      KtButton,
      TableColumnFilterDialog,
      quillEditor,
      LabelSelection
    },
    data() {
      return {
        loading:false,
        showTemplateContent:true,//模板内容展示
        imgUpload: this.utils.imghost,
        typeList: [{value: '1', label: '短信模板'}, {value: '2', label: '邮件模板'}],
        size: "mini",
        filters: {
          templateName: "",
          templateType: "",
          id: ""
        },
        tableData:[],
        totalSize:0,
        pageRequest: {pageNum: 1, pageSize: 10},
        editDialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        editDialogLookVisible: false,

        // 新增编辑界面数据
        dataForm: {
          templateName: "",
          templateType: "",
          templateContent: "",
          status: 0
        },
        dataFormRules: {
          templateName: [{required: true, message: "请输入模板名称", trigger: "blur"}],
          templateType: [{required: true, message: "请选择模板类型", trigger: "change"}],
          templateContent: [{required: true, message: "请输入模板内容", trigger: "blur"}],
        },

        dataLookForm: {
          templateName: "",
          templateType: "",
          templateContent: "",
        },
        editorOption: {
          theme: 'snow',
          boundary: document.body,
          modules: {
            toolbar: {
              container: toolbarOptions,//
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            },
          },
          placeholder: '请输入模板内容',
          readOnly: false
        },
      };
    },
    methods: {
      //查询
      search:function(){
        this.pageRequest.pageNum=1
        this.findPage()
      },
      //模板类型切换
      changeTemplateType:function(param){
        if(param==1){
          this.showTemplateContent=true
        }else{
          this.showTemplateContent=false
        }
      },
      //上传成功
      uploadSuccess(res, file) {
        // 首先获取富文本编辑器的实例
        let quill = this.$refs.myTextEditor.quill
        // 上传成功所执行
        if (res.code == "0000" && res.data !== null) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片res为服务器返回的数据
          quill.insertEmbed(length, 'image', res.data.imageUrl)
          // 光标移动至文本末端
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        // loading动画消失
        // this.quillUpdateImg = false
      },
      //查看
      handleLook: function (row) {
        if (row.templateType == 1) {
          this.dataLookForm = {
            templateName: row.templateName,
            templateType: "短信模板",
            templateContent: row.templateContent,
          }
        } else {
          this.dataLookForm = {
            templateName:row.templateName,
            templateType: "邮件模板",
            templateContent: row.templateContent,
          }
        }
        this.editDialogLookVisible = true
      },
      //新增按钮
      addTemplate() {
        this.showTemplateContent=true
        this.editDialogVisible = true
        this.dataForm = {
          templateName: "",
          templateType: "",
          templateContent: "",
          status: 0
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        });
      },
      // 获取分页数据
      findPage: function (data) {
        if (data != null && data.start != null) {
          if (data.start != null) {
            this.pageRequest.pageNum = data.start;
          }
          if (data.limit != null) {
            this.pageRequest.pageSize = data.limit;
          }
        }
        let this_ = this;
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = this.pageRequest.pageNum;
        this_.filters.limit = this.pageRequest.pageSize;
        this_.loading=true;
        this.utils.request.getTemplateListPage(this_.filters, function (res) {
          if (res.code == "0000") {
            this_.tableData = res.data.rows
            this_.totalSize = res.data.total
          } else {
            this_.tableData = []
            this_.totalSize = 0
          }
          this_.$nextTick(()=>{
            this_.loading=false;
          })
        });
      },

      //模板类型formatter
      typeFormatter: function (row, column, cellValue, index) {
        if (cellValue == "1") {
          return '短信模板'
        } else if (cellValue == "2") {
          return '邮件模板'
        } else {
          return "-"
        }
      },

      //模板状态formatter
      statusFormatter: function (row, column, cellValue, index) {
        if (cellValue == "0") {
          return '正在审核'
        } else if (cellValue == "1") {
          return '审核通过'
        } else if (cellValue == "2") {
          return '审核未通过'
        } else {
          return "-"
        }
      },

      // 编辑,修改
      submitForm: function () {
        let this_ = this
        this.$refs.dataForm.validate(valid => {
          let param = {}
          param.templateName = this_.dataForm.templateName
          if (valid) {
            this_.utils.request.getTemplateListByName(param, function (res) {
              if (res.data.length == 0) {
                if (this_.validateTemplateContent(this_.dataForm.templateContent)) {
                  this_.editLoading = true
                  let params = Object.assign({}, this_.dataForm);
                  this_.utils.request.saveTemplate(params, function (res1) {
                    if (res1.code == "0000") {
                      this_.$message({message: "操作成功", type: "success"});
                      this_.editDialogVisible = false;
                      this_.editLoading = false
                      this_.findPage();
                    } else {
                      this_.$message({message: "操作失败, " + res1.msg, type: "error"});
                      this_.editLoading = false
                    }
                  });
                } else {
                  this_.$message({message: "变量值必须是闭合的", type: "warning"});
                }
              } else {
                this_.$message({message: "模板名称不可重复", type: "warning"});
              }
            })
          }
        });
      },

      //模板内容变量值校验
      validateTemplateContent: function (str) {
        //判断是否有'${'
        if (str.indexOf('${') == -1) {
          return true
        } else {
          let arr = [...str];
          let stack = [];
          for (let i = 0; i < arr.length; ++i) {
            if (arr[i] == "{") {
              stack.push("{");
            } else if (arr[i] == "}") {
              if (stack.length === 0) {
                return false;
              }
              stack.pop()
            }
          }
          return stack.length === 0;
        }
        // let pattern = /[1-9]\d*/
        // let str1 = 11;
      },

      resetForm(formName) {
        if (this.filters.templateName == "" && this.filters.templateType == "" && this.filters.id == "") {
          this.$message({message: "请输入查询条件", type: "warning"});
          return false
        }
        this.filters = {
          templateName: "",
          templateType: "",
          id: ""
        }
        this.pageRequest.pageNum=1
        this.findPage()
      },

      // 处理表格列过滤显示
      displayFilterColumnsDialog: function () {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns: function (data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      // 每页数据刷新
      refreshPageRequest: function (pageNum) {
        this.pageRequest.pageNum = pageNum;
        this.findPage()
      },
      // 每页条数刷新
      handleSizeChange: function (pageSize) {
        this.pageRequest.pageSize = pageSize;
        this.findPage()
      },
    },
    mounted() {
      this.findPage()
    }
  };
</script>

<style scoped lang='scss'>
.mb10{
  margin-bottom: 10px !important;
}
  .desc{
    color: #ffb100;
    font-size: 10px;
    margin-top: 10px;
  }
  .type {
    display: flex;
    align-items: center;
  }

  .type p {
    text-align: right;
    margin-right: 20px;
    width: 120px;
  }

  .newUserOrder {
    margin-top: 2%;
    width: 20%;
    margin-left: 2%;
  }

  .font {
    font-size: 18px;
    font-weight: 800;
  }

  .ruleDes {
    color: #ffdead;
    font-size: 20px;
  }

  .positionDes {
    text-align: center;
    margin-top: 2%;
  }

  .ruleClass {
    font-size: 30px;
  }

  .everyCostHandleSel {
    /deep/ .el-input {
      width: 20%;
    }
  }

  .longInput {
    .timePicker {
      /deep/ .el-input {
        width: 201px !important;
      }
    }
  }

  .alignment {
    display: inline-block;
    height: 32px;
    line-height: 32px;
    font-size: 16px;
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        /deep/ .el-form-item__label {
          margin-right: 10px
        }
      }
    }
  }

  .input100 {
    /deep/ .el-input {
      width: 82px !important;
    }
  }

  .mb18 {
    margin-bottom: 18px;
  }

  .mt18 {
    margin-top: 18px;
  }

  // dialog标题的样式问题
  .span-title {
    font-size: 28px;
    color: #333333;
  }

  //下拉选择框icon对齐
  .iconAlignment {
    /deep/ .el-input__icon {
      line-height: 32px !important;
    }
  }

  .mb120 {
    margin-bottom: 120px !important;
  }

  .mr60 {
    margin-right: 60px !important;
  }

  /deep/ .w138 {
    width: 138px !important;
    /deep/ .el-input__inner {
      width: 138px !important;
    }
  }

  /deep/ .w350 {
    width: 350px !important;
    /deep/ .el-input__inner {
      width: 350px !important;
    }
  }

  .textRed {
    color: red !important;
  }

  .noMarginL {
    margin-left: 0 !important;
  }

  .w70 {
    display: inline-block;
    width: 70px !important
  }

  .colorOrange {
    color: #E7AA4E !important;
  }

  .turnInlineBlock {
    display: inline-block !important;
  }

  .successImg {
    width: 18px;
    height: 18px;
    vertical-align: middle;
  }

  // /deep/ .el-form-item__error{
  //   left: 100px;
  // }
  /deep/ .w115 {
    display: inline-block;
    width: 110px;
    text-align: right;
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      width: 610px;
      padding-left: 40px;
      padding-right: 40px;
      padding-bottom: 40px;
      /deep/ .el-dialog__body {
        padding: 40px 0 0 0;
      }
    }
  }

  .mb40 {
    margin-bottom: 40px;
  }

  .labelText {
    color: #999999;
    font-size: 16px;
  }

  .w125 {
    display: inline-block;
    width: 125px;
    text-align: right
  }

  .w90 {
    display: inline-block;
    width: 90px;
    text-align: right;
  }

  /deep/ .editDialogInput125 {
    width: 125px !important;
    /deep/ .el-input__inner {
      width: 125px !important;
    }
  }

  /deep/ .editDialogInput78 {
    width: 78px !important;
    /deep/ .el-input__inner {
      width: 78px !important;
    }
  }

  /deep/ .w275 {
    width: 275px !important;
    /deep/ .el-input__inner {
      width: 275px !important;
    }
  }

  .color000 {
    color: #000000;
  }

  .color333 {
    color: #333333;
  }

  .color666 {
    color: #666666;
  }

  .textColAlignment {
    display: inline-block;
    height: 32px;
    line-height: 32px;
  }

  .labelNoHeight {
    /deep/ .el-form-item__label {
      height: auto !important;
      line-height: 1 !important;
    }
  }

  .p_d40 {
    padding-left: 40px;
  }

  .w200 {
    /deep/ .el-input {
      width: 200px !important;
      /deep/ .el-input__inner {
        width: 200px !important;
      }
    }
  }

  .errorInfoPosition {
    /deep/ .el-form-item__error {
      left: 112px;
    }
  }

  .labelTextColor666 {
    /deep/ .el-form-item__label {
      color: #666666;
    }
  }

  .formItemNoMargin {
    margin-bottom: 0 !important;
  }

  .form-item-content-noMargin {
    /deep/ .el-form-item__content {
      margin-right: 0 !important;
    }
  }

  .width280 {
    width: 280px !important;
  }

  .m_l5 {
    margin-left: 5px !important;
  }

  .m_l10 {
    margin-left: 10px !important;
  }

  /deep/ .textBtn {
    padding: 0 5px !important;
  }

  .mr5 {
    margin-right: 5px;
  }

  .w108 {
    width: 108px;
  }

  .labelMarginRight10 {
    /deep/ .el-form-item__label {
      margin-right: 10px !important;
    }
  }

  /deep/ .w356 {
    width: 356px !important;
    /deep/ .el-input__inner {
      width: 356px !important;
    }
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        /deep/ .el-form-item__label {
          margin-right: 0 !important;
        }
      }
    }
  }

  .w150 {
    /deep/ .el-input {
      width: 150px !important;
      /deep/ .el-input__inner {
        width: 150px;
      }
    }
  }

  /deep/ .inputInner_paddingRight16 {
    /deep/ .el-input__inner {
      padding-right: 16px !important;
    }
  }

  .width267 {
    width: 267px !important;
  }

  .noPadding {
    padding: 0 !important;
  }

  .w78 {
    width: 78px;
  }

  /deep/ .el-dialog__footer {
    padding: 0 !important;
  }

  .mb90 {
    margin-bottom: 90px !important;
  }

  .w300 {
    width: 300px !important;
  }

  .w316 {
    width: 316px !important;
  }

  .w250 {
    width: 250px !important;
  }

  .contentAlignment {
    height: auto !important;
    line-height: 1 !important;
  }

  .successImg {
    width: 18px;
    height: 18px;
    vertical-align: middle;
  }

  .search-input {
    .times {
      .times-to {
        padding: 0 10px;
        height: 32px;
        line-height: 32px;
        color: #999;
        display: inline-block;
      }
      /deep/ .el-input {
        width: auto !important;
        /deep/ .el-input__inner {
          width: auto !important;
        }
      }
    }
  }
  /deep/ .w760{
    width: 760px !important;
    .el-input__inner{
      width: 760px !important;
    }
  }
  .ml90{
    margin-left: 90px !important;
  }
  .mb5{
    margin-bottom: 5px !important;
  }
  .mt10{
    margin-top: 10px;
  }
</style>
